<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 题
 *
 * @icon fa fa-question
 */
class Question extends Backend
{

    /**
     * Question模型对象
     * @var \app\admin\model\Question
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Question;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("qStatusList", $this->model->getQStatusList());
        $group = Db::name('auth_group_access')->where('uid', $this->auth->id)->find()['group_id'];
        $this->view->assign("group",$group);
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $this->assign("ids", $ids);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ids = input('ids');
            if ($ids) {
                $where1['question.bank_id'] = $ids;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['questionbank'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['questionbank'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'type', 'score', 'difficulty', 'q_info', 'answer', 'comm', 'q_status']);
                $row->visible(['questionbank']);
                $row->getRelation('questionbank')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $userId = Db::name('teacher')->where('admin_id', $this->auth->id)->field('id')->find()['id'];
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $question_items = $params['question_items'];
                    //释放数组中的key
                    unset($params['question_items']);
                    $params['create_time'] = date("Y-m-d H:i:s");
                    $params['create_user'] = $userId;
                    $result = $this->model->allowField(true)->save($params);
                    $lastQid = Db::name('question')->getLastInsID();
                    $question_items_array = json_decode($question_items, true);
                    foreach ($question_items_array as $key => &$value) {
                        $value['question_id'] = $lastQid;
                    }
                    Db::name("question_item")->insertAll($question_items_array);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $ids = input('ids');
        $row['bank_id'] = $ids;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $question_id = $params['id'];
                    $question_items = $params['question_items'];
                    $question_items_array = json_decode($question_items, true);
                    Db::name('question_item')->where('question_id', $question_id)->delete();
                    unset($params['question_items']);
                    Db::name("question_item")->insertAll($question_items_array);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //查询对应的题项信息
        $question_items = Db::name("question_item")->where('question_id', '=', $ids)->select();
        $row['question_items'] = json_encode($question_items);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
